import tkinter as tk
import tkinter.font as tkFont
import tkinter.ttk as ttk
from tkinter import filedialog
from tkinter import messagebox
import threading
from tkinter import *
from geatpy import bs2ri, crtpc, ranking

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2Tk
from genetic_algorithm import *


class MainWindow(tk.Frame):
    """继承自Frame类，master为Tk类顶级窗体（带标题栏、最大、最小、关闭按钮）"""
    ft = None
    panewin = None
    frm_left = None
    frm_right = None
    route_canvas = None
    circle_canvas = None
    frm_control = None
    file_path = []
    file_text = ['平面参数', '纵断面参数', '超高', '道床高度']
    thread = None
    bi_ori = None
    bi_now = None
    def __init__(self, master=None):
        super().__init__(master)
        self.init_component(master)
    def init_component(self, master):
        """初始化GUI组件"""
        # 设置顶级窗体的行列权重，否则子组件的拉伸不会填充整个窗体
        self.bi_ori = StringVar()
        self.bi_now = StringVar()
        self.bi_ori.set("初始侵限值："+str(cal_ori()))
        self.bi_now.set("None")
        master.geometry('800x480+200+100')
        master.title('metro')
        master.minsize(800, 480)
        master.rowconfigure(0, weight=1)
        master.columnconfigure(0, weight=1)
        self.ft = tkFont.Font(family='微软雅黑', size=12, weight='bold')  # 创建字体      
        # 设置继承类MWindow的grid布局位置，并向四个方向拉伸以填充顶级窗体
        self.grid(row=0, column=0, sticky=tk.NSEW)
        # 设置继承类MWindow的行列权重，保证内建子组件会拉伸填充
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.panewin = ttk.Panedwindow(self, orient=tk.HORIZONTAL)  # 添加水平方向的推拉窗组件
        self.panewin.grid(row=0, column=0, sticky=tk.NSEW)  # 向四个方向拉伸填满MWindow帧
        self.frm_left = ttk.Frame(self.panewin, relief=tk.SUNKEN, padding=0)  # 左侧Frame帧用于放置播放列表
        self.frm_left.grid(row=0, column=0, sticky=tk.NSEW)  # 左侧Frame帧拉伸填充
        self.panewin.add(self.frm_left, weight=20)  # 将左侧Frame帧添加到推拉窗控件，左侧权重20
        self.init_left()  # 添加canvas
        self.frm_right = ttk.Frame(self.panewin, relief=tk.SUNKEN)  # 右侧Frame帧用于放置视频区域和控制按钮
        self.frm_right.grid(row=0, column=0, sticky=tk.NS)  # 右侧Frame帧四个方向拉伸
        self.frm_right.columnconfigure(0, weight=1)  # 右侧Frame帧两行一列，配置列的权重
        self.frm_right.rowconfigure(0, weight=80)  # 右侧Frame帧两行的权重80:1
        self.frm_right.rowconfigure(1, weight=1)
        self.panewin.add(self.frm_right, weight=1)  # 将右侧Frame帧添加到推拉窗控件,右侧权重1
        s = ttk.Style()
        s.configure('www.TFrame')  # Frame帧添加样式

        # 右侧Frame帧第一行添加路线canvas
        self.route_canvas = tk.Canvas(self.frm_right, relief=tk.RIDGE, background='white')
        self.route_canvas.grid(row=1, column=0, sticky=tk.NSEW)
        # 右侧Frame帧第二行添加控制按钮
        self.frm_control = ttk.Frame(self.frm_right, relief=tk.RAISED)  # 四个方向拉伸
        self.frm_control.grid(row=0, column=0, sticky=tk.NSEW)
        self.init_right_top()  # 添加按钮

    def init_left(self):
        """初始化树状视图"""
        self.frm_left.rowconfigure(0, weight=1)  # 左侧Frame帧行列权重配置以便子元素填充布局                 
        self.frm_left.columnconfigure(0, weight=1)  # 左侧Frame帧中添加树状视图
        self.circle_canvas = tk.Canvas(self.frm_left, background='white')
        self.circle_canvas.grid(row=0, column=0, sticky=tk.NSEW)  # 树状视图填充左侧Frame帧


    def choose_file(self, i):
        file_name = tk.filedialog.askopenfilename(
            filetypes=[("TXT", ".txt")])
        if len(file_name) > 0:
            self.file_path[i].set(str(file_name))
            self.update()

    def start(self):
        for t in self.file_path:
            if t.get() in ['请选择{}文件'.format(i) for i in self.file_text]:
                tk.messagebox.showwarning('warning', t.get())
                return
        self.thread = threading.Thread(target=run, args=(self.circle_canvas,self.route_canvas,self.bi_ori,self.bi_now,self))
        self.thread.start()

    def init_right_top(self):
        """初始化按钮们"""
        self.frm_control.columnconfigure(0, weight=1)  # 配置控制区Frame各行列的权重
        i = 0
        for _text in self.file_text:
            frm_btn = ttk.Frame(self.frm_control, padding=2)
            frm_btn.grid(row=i, column=0, sticky=tk.NSEW)
            ttk.Button(frm_btn, text=_text, command=lambda j=i: self.choose_file(j)).grid(row=0, column=0)
            self.file_path.append(tk.StringVar())
            self.file_path[i].set('请选择{}文件'.format(_text))
            ttk.Label(frm_btn, textvariable=self.file_path[i]).grid(row=0, column=1, padx=10)
            self.frm_control.rowconfigure(i, weight=1)
            i += 1
        te = cal_ori()
        self.bi_ori.set("初始侵限值："+str(te[0]/te[1]))
        self.bi_now.set("当前最优侵限值：None")
        frm_btn = ttk.Frame(self.frm_control, padding=2)
        frm_btn.grid(row=i, column=0, sticky=tk.NSEW)
        l1 = Label(master=frm_btn, textvariable=self.bi_ori)
        l1.grid(row=0, column=0)
        ttk.Label(master=frm_btn, textvariable=self.bi_now).grid(row=0, column=1, padx=10)
        print(self.bi_now.get())
        ttk.Button(frm_btn, text='开始运行', command=self.start).grid(row=0, column=2)
        self.frm_control.rowconfigure(i, weight=1)


if __name__ == '__main__':
    root = tk.Tk()
    app = MainWindow(root)
    root.mainloop()
